<template>
  <div class="template-container">
    <div class="template-header">
      <h1>法律文档表单编辑器</h1>
      <p>拖拽组件快速生成法律文档表单</p>
    </div>

    <div class="template-content">
      <!-- 左侧组件面板 -->
      <div class="components-panel">
        <h3>表单组件</h3>
        <div class="components-list">
          <div
            v-for="component in formComponents"
            :key="component.type"
            class="component-item"
            draggable="true"
            @dragstart="onDragStart(component)"
          >
            <el-icon class="component-icon">
              <component :is="component.icon" />
            </el-icon>
            <span>{{ component.name }}</span>
          </div>
        </div>
      </div>

      <!-- 中间设计区域 -->
      <div class="design-area" @drop="onDrop" @dragover.prevent>
        <div class="design-header">
          <el-button type="primary" @click="previewForm">预览表单</el-button>
          <el-button @click="saveTemplate">保存模板</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>

        <el-form ref="designForm" :model="formData" label-width="120px" class="form-design-area">
          <draggable
            v-model="formFields"
            item-key="id"
            class="draggable-list"
            @start="drag = true"
            @end="drag = false"
          >
            <template #item="{ element, index }">
              <div
                class="form-field-item"
                :class="{ active: activeFieldIndex === index }"
                @click="setActiveField(index)"
              >
                <div class="field-header">
                  <span class="field-title">{{ element.label }}</span>
                  <div class="field-actions">
                    <el-button type="danger" text size="small" @click="removeField(index)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>

                <!-- 动态渲染表单字段 -->
                <el-form-item :label="element.label" :prop="element.model">
                  <component
                    :is="getComponent(element.type)"
                    v-model="formData[element.model]"
                    v-bind="element.props"
                    :placeholder="element.placeholder"
                    style="width: 100%"
                  />
                </el-form-item>
              </div>
            </template>
          </draggable>

          <div v-if="formFields.length === 0" class="empty-tip">
            <el-empty description="从左侧拖拽组件到此处开始设计表单" />
          </div>
        </el-form>
      </div>

      <!-- 右侧属性配置面板 -->
      <div class="properties-panel" v-if="activeField">
        <h3>字段属性</h3>
        <el-form :model="activeField" label-width="80px">
          <el-form-item label="字段标签">
            <el-input v-model="activeField.label" />
          </el-form-item>

          <el-form-item label="字段名">
            <el-input v-model="activeField.model" />
          </el-form-item>

          <el-form-item label="占位符">
            <el-input v-model="activeField.placeholder" />
          </el-form-item>

          <el-form-item label="是否必填">
            <el-switch v-model="activeField.required" />
          </el-form-item>

          <!-- 根据字段类型显示不同的配置选项 -->
          <template v-if="activeField.type === 'select'">
            <el-form-item label="选项">
              <div v-for="(option, idx) in activeField.options" :key="idx" class="option-item">
                <el-input
                  v-model="option.label"
                  placeholder="选项标签"
                  style="margin-bottom: 5px"
                />
                <el-input v-model="option.value" placeholder="选项值" />
                <el-button type="danger" text @click="removeOption(idx)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
              <el-button @click="addOption">添加选项</el-button>
            </el-form-item>
          </template>

          <template v-if="activeField.type === 'date'">
            <el-form-item label="日期类型">
              <el-select v-model="activeField.dateType">
                <el-option label="日期" value="date" />
                <el-option label="日期时间" value="datetime" />
                <el-option label="日期范围" value="daterange" />
              </el-select>
            </el-form-item>
          </template>
        </el-form>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" title="表单预览" width="600px">
      <el-form :model="previewData" label-width="120px">
        <el-form-item
          v-for="field in formFields"
          :key="field.id"
          :label="field.label"
          :rules="field.required ? [{ required: true, message: `请输入${field.label}` }] : []"
        >
          <component
            :is="getComponent(field.type)"
            v-model="previewData[field.model]"
            v-bind="field.props"
            :placeholder="field.placeholder"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="previewVisible = false">关闭</el-button>
        <el-button type="primary" @click="submitPreview">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Edit, Calendar, Select, Switch, Upload, Delete } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'

// 可用的表单组件
const formComponents = [
  { type: 'input', name: '单行文本', icon: Edit },
  { type: 'textarea', name: '多行文本', icon: Document },
  { type: 'select', name: '下拉选择', icon: Select },
  { type: 'date', name: '日期选择', icon: Calendar },
  { type: 'switch', name: '开关', icon: Switch },
  { type: 'upload', name: '文件上传', icon: Upload },
]

// 表单字段数据
const formFields = ref([])
const formData = ref({})
const previewData = ref({})

// 当前激活的字段
const activeFieldIndex = ref(-1)
const activeField = computed(() => {
  return activeFieldIndex.value >= 0 ? formFields.value[activeFieldIndex.value] : null
})

// 预览对话框
const previewVisible = ref(false)

// 设置激活字段
const setActiveField = (index) => {
  activeFieldIndex.value = index
}

// 移除字段
const removeField = (index) => {
  formFields.value.splice(index, 1)
  if (activeFieldIndex.value === index) {
    activeFieldIndex.value = -1
  }
}

// 拖拽开始
const onDragStart = (component) => {
  event.dataTransfer.setData('componentType', component.type)
}

// 拖拽放置
const onDrop = (event) => {
  const componentType = event.dataTransfer.getData('componentType')
  addFormField(componentType)
}

// 添加表单字段
const addFormField = (type) => {
  const fieldId = Date.now().toString()
  const baseField = {
    id: fieldId,
    type: type,
    model: `field_${fieldId}`,
    label: `字段${formFields.value.length + 1}`,
    placeholder: `请输入${getComponentName(type)}`,
    required: false,
    props: {},
  }

  // 根据类型添加特定配置
  switch (type) {
    case 'select':
      baseField.options = [
        { label: '选项1', value: 'option1' },
        { label: '选项2', value: 'option2' },
      ]
      break
    case 'date':
      baseField.dateType = 'date'
      break
    case 'upload':
      baseField.props = {
        action: '/api/upload',
        multiple: false,
      }
      break
  }

  formFields.value.push(baseField)
  formData.value[baseField.model] = ''
  setActiveField(formFields.value.length - 1)
}

// 获取组件名称
const getComponentName = (type) => {
  const component = formComponents.find((c) => c.type === type)
  return component ? component.name : '字段'
}

// 获取对应的Element Plus组件
const getComponent = (type) => {
  const componentMap = {
    input: 'el-input',
    textarea: 'el-input',
    select: 'el-select',
    date: 'el-date-picker',
    switch: 'el-switch',
    upload: 'el-upload',
  }

  const component = componentMap[type] || 'el-input'

  // 特殊处理textarea
  if (type === 'textarea') {
    return {
      template: '<el-input type="textarea" v-bind="$attrs" v-on="$listeners" />',
    }
  }

  return component
}

// 选择框选项管理
const addOption = () => {
  if (activeField.value && activeField.value.options) {
    activeField.value.options.push({ label: '', value: '' })
  }
}

const removeOption = (index) => {
  if (activeField.value && activeField.value.options) {
    activeField.value.options.splice(index, 1)
  }
}

// 预览表单
const previewForm = () => {
  previewData.value = { ...formData.value }
  previewVisible.value = true
}

// 提交预览
const submitPreview = () => {
  ElMessage.success('表单提交成功！')
  previewVisible.value = false
}

// 保存模板
const saveTemplate = async () => {
  if (formFields.value.length === 0) {
    ElMessage.warning('请先设计表单')
    return
  }

  try {
    const templateData = {
      fields: formFields.value,
      createdAt: new Date().toISOString(),
    }

    // 这里可以调用API保存到后端
    localStorage.setItem('lawFormTemplate', JSON.stringify(templateData))
    ElMessage.success('模板保存成功！')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 重置表单
const resetForm = async () => {
  try {
    await ElMessageBox.confirm('确定要重置所有表单字段吗？', '提示', {
      type: 'warning',
    })

    formFields.value = []
    formData.value = {}
    activeFieldIndex.value = -1
    ElMessage.success('重置成功')
  } catch {
    // 用户取消
  }
}

// 加载保存的模板
const loadTemplate = () => {
  const saved = localStorage.getItem('lawFormTemplate')
  if (saved) {
    try {
      const template = JSON.parse(saved)
      formFields.value = template.fields
      // 初始化表单数据
      formFields.value.forEach((field) => {
        formData.value[field.model] = ''
      })
    } catch (error) {
      console.error('加载模板失败:', error)
    }
  }
}

onMounted(() => {
  loadTemplate()
})
</script>

<style scoped>
.template-container {
  height: 100vh;
  background: #f5f7fa;
}

.template-header {
  background: white;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
  text-align: center;
}

.template-header h1 {
  margin: 0;
  color: #303133;
}

.template-header p {
  margin: 5px 0 0;
  color: #909399;
}

.template-content {
  display: flex;
  height: calc(100vh - 120px);
}

.components-panel {
  width: 250px;
  background: white;
  border-right: 1px solid #e4e7ed;
  padding: 20px;
}

.components-panel h3 {
  margin-top: 0;
  color: #303133;
}

.components-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.component-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  cursor: grab;
  transition: all 0.3s;
}

.component-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.component-icon {
  margin-right: 8px;
  color: #409eff;
}

.design-area {
  flex: 1;
  background: white;
  margin: 0 20px;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.design-header {
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  gap: 10px;
}

.form-design-area {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.draggable-list {
  min-height: 200px;
}

.form-field-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 16px;
  transition: all 0.3s;
  position: relative;
}

.form-field-item.active {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.form-field-item:hover {
  border-color: #c0c4cc;
}

.field-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.field-title {
  font-weight: 500;
  color: #303133;
}

.field-actions {
  opacity: 0;
  transition: opacity 0.3s;
}

.form-field-item:hover .field-actions {
  opacity: 1;
}

:deep(.el-form-item) {
  margin-bottom: 0;
  padding: 16px;
}

.empty-tip {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.properties-panel {
  width: 300px;
  background: white;
  border-left: 1px solid #e4e7ed;
  padding: 20px;
  overflow-y: auto;
}

.properties-panel h3 {
  margin-top: 0;
  color: #303133;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.option-item :deep(.el-input) {
  flex: 1;
}
</style>
